#!/usr/bin/env python

# Import modules.
import sys
import os
import argparse
import time
import serial

# Define variables.
global file_input
global file_length
global file_name
global serial_port
global serial_speed
file_name = None
file_length = None
file_input = None

# Get command line arguments.
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file_name", action="store", help="the file to work on")
parser.add_argument("-s", "--serial_speed", required=True, action="store", help="serial port speed")
parser.add_argument("-p", "--serial_port", required=True, action="store", help="serial port device")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-l", "--list", action="store_true", help="list files on the module")
group.add_argument("-w", "--write", action="store_true", help="write a file to the module")
group.add_argument("-d", "--delete", action="store_true", help="delete a file from the module")
group.add_argument("-e", "--enable", action="store_true", help="enable a file on the module")
args = parser.parse_args()
serial_port = args.serial_port
serial_speed = args.serial_speed
file_name = args.file_name

def main():
  if args.list:
    list_files()
  elif args.write:
    get_file()
    write_file()
  elif args.delete:
     delete_file()
  elif args.enable:
    enable_file()

def get_file():
	global file_input
	global file_length
	global file_name
#	absFileName = os.path.abspath(setWorkingDir.codeDir+options.FILE)	#the full path of the file
	print "Opening:"+ file_name		
	file = open(file_name,'r')
	file_input = file.readlines()
	file_length = os.path.getsize(file_name)
	for line in file_input:
		pass
		#file_length += 0 #add 1 onto each line	

def write_file():
	global file_input
	global file_length
	global file_name
	
	print "writing file:"
	print file_name
	print file_length

   if int(file_length)>7200:
    print "#### FILE TOO BIG 7200 byte max #####"
     sys.exit(1)		
   write_command= "AT#WSCRIPT=%s,%i\r\n" % (file_name,file_length)
   print "Sending:" + write_command
   serial_open_check()			#open serial connection send AT to check
   telit_port.flushInput()			#get rid of junk
   telit_port.write(write_command)
   input = get_reply()			#from setPort
   if ">>>" not in input:
     print "didn't get >>>??"
     print input		
     sys.exit(1)
   print"START FILE#########"
   line_marker=0
  for line in file_input:
     try:	#two from back is /n/l
       if(line[-1:] == "\r\n"):
         write_line=line
      #it is somthing else append \r\n
       else:
         write_line=line#[:-1] + "\r\n"
			#write out to port
			telit_port.write(write_line)
			##print what we wrote
			#print "%i: %s" % (line_marker,write_line)
			line_marker+=1
		#	time.sleep(.1) #sleep a bit to see the line
		except serial.serialutil.SerialTimeoutException:
			print "serial timed out on line " + line_marker	
			serial_close()
			sys.exit(1)
	input = get_reply()
	for line in input:
		if "OK\r\n" in line:
			print "loaded OK"
			break
	else:
     print input
	telit_port.flush()
	print"END FILE###########"

def delete_file():
	global file_length
	global file_name
	
	serial_open_check()				#open serial connection send AT to check
	delete_command= "AT#DSCRIPT=%s\r\n" % (file_name)
	if ".py" in file_name:
		print "\nDELETING .py file:"
		#delete both files .py and .pyo
		print "Sending: " + delete_command
		telit_port.flush()
		telit_port.write(delete_command)
		input = get_reply()
		for lines in input:
			if "OK" in lines:
				print "FOUND AND DELETED:" +file_name
				break	
			elif "ERROR" in lines:
				print "didn't find .py file: " +file_name
				print lines
				break
		#delete .pyo
		print "\nDELETING .pyo file:"
		delete_command= "AT#DSCRIPT=%so\r\n" % (file_name) #add 'o' for pyo
		print "Sending: " + delete_command
		telit_port.flushInput()
		telit_port.write(delete_command)
		input = get_reply()
		for lines in input:
			if "OK" in lines:
				print "FOUND AND DELETED:" +file_name+"o"
				break
			elif "ERROR" in lines:
				print "didn't find .pyo file: " +file_name
				print lines
				break
	else:
		print "\nDELETING file:"
		#delete file
		print "Sending: " + delete_command
		telit_port.flush()
		telit_port.write(delete_command)
		input = get_reply()
		for lines in input:
			if "OK" in lines:
				print "FOUND AND DELETED:" +file_name
				break	
			elif "ERROR" in lines:
				print "didn't find .py file: " +file_name
				print lines
				break

	serial_close()

# List files.
def list_files():
	global file_length
	global file_name
	
	if file_name is None:				#set impossible
		file_name="spoogert"
		file_length=1000000000
	serial_open_check()			#open serial connection send AT to check
	list_command= "AT#LSCRIPT\r\n" 
	print "Listing current files:"
	print "Sending: " + list_command
	telit_port.flush()
	telit_port.write(list_command)
	input = get_reply()
	found_file="false"
	for line in input:
		print line
		if "#LSCRIPT: \"%s\",%i" % (file_name,file_length) in line:
			print "*******************************FOUND FILE->" +file_name
			found_file="true"	
	if found_file == "true":
		print "#########################################"
		print "FILE: " +file_name + " is stored on Telit.."
		print "#########################################"
	
	serial_close()
	return input

# Read file.
def read_file():
	global file_name
	serial_open_check()			#open serial connection send AT to check
	read_command = "AT#RSCRIPT=\"%s\"\r\n" % (file_name)
	print "Reading file: " + file_name
	print "Sending: " + read_command
	telit_port.flush()
	telit_port.write(read_command)
#	input = get_reply()
	input = telit_port.readlines()
	#write to log file
	log_file= open("../log_file.txt", 'w')	#overwrite eachtime
	line_marker=0
	for line in input:
		log_file.write(line)
		time.sleep(.1)
		print "%i: %s"%(line_marker,line)
		line_marker+=1
	print "done reading"
	log_file.close()

# Enable script.
def enable_script():
   global file_name
   serial_open_check()			#open serial connection send AT to check
   if file_name == None:
     enable_command = "AT#ESCRIPT?\r\n" 
  else:
    enable_command = "AT#ESCRIPT=\"%s\"\r\n" % (file_name)
    print "SETTING MAIN() SCRIPT AS: " + file_name
  print "Sending: " + enable_command
  telit_port.flush()
   telit_port.write(enable_command)
   input = get_reply()
   print "STATUS:"
   for line in input:
     print line
  serial_close()

# Delete all files.
def delete_all():
	global file_name 
	files=list_files()				#list files get names
	for file in files:		
		if file.find('"') != -1:		#if it has " it has file name
			deleteMe = file.split('"')[1]	#just get file name
			print "FOUND: " + deleteMe	
			file_name = deleteMe		#set global to pass to delete_file
			delete_file()			#delete file_name

def TESTSERIAL():
	serial_open_check()
	serial_close()

def READFILE():
	get_fileOption()
	read_file()

def LISTFILE():
	list_files()

def FINDFILE():
	get_fileOption()
	list_files()

def DELETEFILE():
	get_fileOption()
	delete_file()

def DELETEALL():
	delete_all()

def WRITEFILE():
	get_file()
	delete_file()
	write_file()

def WRITECHECKFILE():
	get_file()
	write_file()
	read_file()

def ENABLESCRIPT():
	get_fileOption()
	enable_script()

def CHECKENABLE():
	enable_script()

def get_reply(time_sleep=.1):
   global telit_port
   tooLong = time.time()+10
   while telit_port.inWaiting() < 3 : 	
     time.sleep(1)			#You have to sleep you can't hammer the processor
     if time.time() > tooLong:
       ERROR="ERROR"
       return ERROR		#timeout somthing went wrong	
     else:
      time.sleep(time_sleep) #wait half second for all data
      input = telit_port.readlines()
  return input

def heart_beat():
	global telit_port
	telit_port.flushInput() #clear buffer of junk
	telit_port.write("AT\r") #send a AT<CR>
	input = get_reply()	

  if "OK\r\n" not in input:
    print "Failed to talk to Telit, is it on? Is the port free?"
    print "Try to figure it out and try again"
    sys.exit(1)
  else:
    print "Telit replied, communications OK....."
    return True

def open_serial():
	global telit_port
	try:
     telit_port = serial.Serial(serial_port,serial_speed,rtscts=0,xonxoff=0,timeout=1,bytesize=8,stopbits=1,parity='N',writeTimeout=1)
    telit_port.open()
  except serial.SerialException,e:
		print "SERIAL FAILURE: ",e
		sys.exit(1) #bad for UNIX
  if heart_beat():
		return True

def serial_open_check():
	open_serial()
	return True

def serial_close():
	global telit_port
	telit_port.close()

if __name__ == "__main__":
	main()
